package com.demo.scenic.service.impl;

import com.demo.scenic.common.BaseResponse;
import com.demo.scenic.service.UploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Service
public class UploadServiceImpl implements UploadService {

    @Value("${upload.path}")
    private String imgPath;

    @Value("${image.url}")
    private String imgUrl;

    @Override
    public BaseResponse uploadImage(MultipartFile file) throws Exception{
        String newFileName;
        if (file.isEmpty()){
            return BaseResponse.fail("文件为空");
        }
        try {
            String fileName = file.getOriginalFilename();
            // 获取文件后缀名
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            // 生成新的文件名
            newFileName = UUID.randomUUID().toString() + "." + suffix;
            File dir = new File(imgPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File newFile = new File(dir, newFileName);
            file.transferTo(newFile);
        }catch (Exception e){
            e.printStackTrace();
            return BaseResponse.fail("上传失败");
        }

        return BaseResponse.ok(imgUrl+ newFileName);
    }
}
